
import socket
import re
import json


class SimpleLuaDebuggerClient:
	def __init__(self):
		pass

	def Connect(self):
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.connect(('localhost', 8173))
		return self.Op('simple')

	def Op(self, op):
		if type(op) == dict:
			op = op['Op']
		self.Send(op)
		return self.Receive()

	def Send(self, op):
		self.sock.send(op+'\n')
	
	def Receive(self):
		# FIXME: receive exactly one line
		s = self.sock.recv(4096)
		if not s:
			return
		m = re.match(r'^(.*):\s*(\d+)$', s)
		file = m.group(1)
		line = int(m.group(2))
		return (file, line)
	
	def Close(self):
		self.sock.close()



class JSONLuaDebuggerClient:
	def __init__(self):
		pass

	def Connect(self):
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.connect(('localhost', 8173))
		return self.Op('json')


	def Op(self, obj):
		self.Send(obj)
		return self.Receive()

	def Send(self, obj):
		# TODO: handle recurisve list/dict
		s = json.write(obj)
		self.sock.send(s+'\n')
	
	def Receive(self):
		s = self.sock.recv(4096)
		if not s:
			return
		obj = json.read(s)
		return obj
	
	def Close(self):
		self.sock.close()


